//
//  ScenePrizedResultsVC.m
//  SMTools
//
//  Created by fengsh on 2019/1/13.
//  Copyright © 2019年 fengsh. All rights reserved.
//

#import "ScenePrizedResultsVC.h"
#import "ScencResults.h"
#import <MagicalRecord/MagicalRecord.h>
#import <QuartzCore/QuartzCore.h>
#include "LibXL/libxl.h"

@interface ScenePrizedResultsVC ()<NSTableViewDelegate,NSTableViewDataSource>
@property (weak) IBOutlet NSTableView *tableview;
@property (weak) IBOutlet NSTextField *tf_name;
@property (weak) IBOutlet NSComboBox *cmb_department;
@property (weak) IBOutlet NSComboBox *cmb_prize_name;
@property (weak) IBOutlet NSTextField *tf_prizeno;
@property (weak) IBOutlet NSTextField *tf_phone;
@property (weak) IBOutlet NSMatrix *excelFormat;
@property (nonatomic, strong) NSMutableArray            *dataset;
@end

@implementation ScenePrizedResultsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    _dataset = [NSMutableArray array];
    
    [self reloadLocaldata];
}

- (void)viewWillAppear
{
    [super viewWillAppear];

    [self reloadLocaldata];
}

- (void)reloadLocaldata
{
    [_cmb_department removeAllItems];
    [_cmb_prize_name removeAllItems];
    NSArray *list = [ScencResults MR_findAllSortedBy:@"createTime" ascending:NO];
    NSArray *prizeNames = [list valueForKey:@"prizeName"];
    NSSet *prizeNameSet = [NSSet setWithArray:prizeNames];
    NSArray *pnames = [prizeNameSet allObjects];
    
    [_cmb_prize_name addItemsWithObjectValues:pnames];
    
    NSArray *departNames = [list valueForKey:@"department"];
    NSSet *departSet = [NSSet setWithArray:departNames];
    NSArray *departs = [departSet allObjects];
    [_cmb_department addItemsWithObjectValues:departs];
    
    [_dataset removeAllObjects];
    [_dataset addObjectsFromArray:list];
    [self.tableview reloadData];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.dataset.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 30;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    
    ScencResults *result = self.dataset[row];
    
    switch (colidx) {
        case 0:
        {
            [cv.textField setStringValue:result.prizeNo?:@""];
        }
            break;
        case 1:
        {
            [cv.textField setStringValue:result.prizeName?:@""];
        }
            break;
        case 2:
        {
            [cv.textField setStringValue:result.name?:@""];
        }
            break;
        case 3:
        {
            [cv.textField setStringValue:result.department?:@""];
        }
            break;
        case 4:
        {
            [cv.textField setStringValue:result.mobile?:@""];
        }
            break;
        case 5:
        {
            [cv.textField setStringValue:[NSString stringWithFormat:@"%d",result.prizeInCount]];
        }
            break;
        case 6:
        {
            NSDate *dt = result.createTime;
            NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
            [fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            [fmt setDateStyle:NSDateFormatterMediumStyle];//设置日期格式，系统提供
            [fmt setTimeStyle:NSDateFormatterShortStyle];//设置时间格式，系统提供
            NSString *dtstring = [fmt stringFromDate:dt];
            [cv.textField setStringValue:dtstring?:@""];
        }
            break;
        case 7:
        {
            [cv.textField setStringValue:result.isremainprize?@"是":@"否"];
        }
            break;
        case 8:
        {
            
        }
            break;
        default:
            break;
    }
    
    return cv;
}

- (IBAction)onSelected:(id)sender
{
    NSString *p = @"";
    NSString *name = self.tf_name.stringValue;
    NSString *mobile = self.tf_phone.stringValue;
    NSString *department = self.cmb_department.stringValue;
    NSString *pname = self.cmb_prize_name.stringValue;
    NSString *pno = self.tf_prizeno.stringValue;
    
    name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    mobile = [mobile stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    department = [department stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    pname = [pname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    pno = [pno stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (name.length > 0) {
        p = [p stringByAppendingString:[NSString stringWithFormat:@"name like '*%@*'",name]];
    }
    
    if (mobile.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and mobile like '*%@*'",mobile]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"mobile like '*%@*'",mobile]];
        }
    }
    
    if (department.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and department like '*%@*'",department]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"department like '*%@*'",department]];
        }
    }
    
    if (pname.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and prizeName like '*%@*'",pname]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"prizeName like '*%@*'",pname]];
        }
    }
    
    if (pno.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and prizeNo like '*%@*'",pno]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"prizeNo like '*%@*'",pno]];
        }
    }
    
    NSArray *list = nil;
    if (p.length > 0) {
        NSPredicate *pre = nil;
        pre = [NSPredicate predicateWithFormat:p];
        list = [ScencResults MR_findAllSortedBy:@"createTime" ascending:NO withPredicate:pre];
    } else {
        list = [ScencResults MR_findAllSortedBy:@"createTime" ascending:NO];
    }
    
    [self.dataset removeAllObjects];
    [self.dataset addObjectsFromArray:list];
    [self.tableview reloadData];
}

- (IBAction)onExportExcel:(id)sender
{
//    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
//    NSString *docementDir = [documents objectAtIndex:0];
//    docementDir = @"/Users/a/Downloads";
//    NSString *filePath = [docementDir stringByAppendingPathComponent:@"Student.csv"];
//
//    [self exportCSV:filePath];
    
    [self test];

}

- (IBAction)onClean:(id)sender {
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        [ScencResults MR_truncateAllInContext:localContext];
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        [self reloadLocaldata];
    }];
}

- (void)exportCSV:(NSString *)fileName
{
    NSOutputStream *output = [[NSOutputStream alloc] initToFileAtPath:fileName append:YES];
    [output open];
    if (![output hasSpaceAvailable]) {
        NSLog(@"没有足够可用空间");
    } else {
        NSString *header = @"学号,姓名\n";   //这里是文件第一行的头（逗号是换列，\n是换行）
        
        const uint8_t *headerString = (const uint8_t *)[header cStringUsingEncoding:NSUTF8StringEncoding];
        NSInteger headerLength = [header lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        NSInteger result = [output write:headerString maxLength:headerLength];
        if (result <= 0) {
            NSLog(@"写入错误");
        }
        
//        NSArray *students = [self queryStudents];
//        for (Student *stu in students) {
//
//            NSString *row = [NSString stringWithFormat:@"%@,%@\n", stu.num, stu.name];   //循环插入数据<span style="font-family: Arial, Helvetica, sans-serif;">（逗号是换列，\n是换行）</span>
//
//            const uint8_t *rowString = (const uint8_t *)[row cStringUsingEncoding:NSUTF8StringEncoding];
//            NSInteger rowLength = [row lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
//            result = [output write:rowString maxLength:rowLength];
//            if (result <= 0) {
//                NSLog(@"无法写入内容");
//            }
//
//        }
        
        [output close];
    }
}

-(void)test
{
    BOOL xlsMode = [[_excelFormat selectedCell] tag];
    
    NSLog(@"createExcel: %@ mode", xlsMode ? @"xls" : @"xlsx");
    
    FontHandle boldFont;
    FontHandle titleFont;
    FormatHandle titleFormat;
    FormatHandle headerFormat;
    FormatHandle descriptionFormat;
    FormatHandle amountFormat;
    FormatHandle totalLabelFormat;
    FormatHandle totalFormat;
    FormatHandle signatureFormat;
    SheetHandle sheet;
    BookHandle book;
    
    book = xlsMode ? xlCreateBook() : xlCreateXMLBook();
    
    boldFont = xlBookAddFont(book, 0);
    xlFontSetBold(boldFont, 1);
    
    titleFont = xlBookAddFont(book, 0);
//    xlFontSetName(titleFont, "Arial Black");
    xlFontSetSize(titleFont, 16);
    
    titleFormat = xlBookAddFormat(book, 0);
    xlFormatSetFont(titleFormat, titleFont);
    
    headerFormat = xlBookAddFormat(book, 0);
    xlFormatSetAlignH(headerFormat, ALIGNH_CENTER);
    xlFormatSetBorder(headerFormat, BORDERSTYLE_THIN);
    xlFormatSetFont(headerFormat, boldFont);
    xlFormatSetFillPattern(headerFormat, FILLPATTERN_SOLID);
    xlFormatSetPatternForegroundColor(headerFormat, COLOR_TAN);
    
    descriptionFormat = xlBookAddFormat(book, 0);
    xlFormatSetBorderLeft(descriptionFormat, BORDERSTYLE_THIN);
    
    amountFormat = xlBookAddFormat(book, 0);
    xlFormatSetNumFormat(amountFormat, NUMFORMAT_CURRENCY_NEGBRA);
    xlFormatSetBorderLeft(amountFormat, BORDERSTYLE_THIN);
    xlFormatSetBorderRight(amountFormat, BORDERSTYLE_THIN);
    
    totalLabelFormat = xlBookAddFormat(book, 0);
    xlFormatSetBorderTop(totalLabelFormat, BORDERSTYLE_THIN);
    xlFormatSetAlignH(totalLabelFormat, ALIGNH_RIGHT);
    xlFormatSetFont(totalLabelFormat, boldFont);
    
    totalFormat = xlBookAddFormat(book, 0);
    xlFormatSetNumFormat(totalFormat, NUMFORMAT_CURRENCY_NEGBRA);
    xlFormatSetBorder(totalFormat, BORDERSTYLE_THIN);
    xlFormatSetFont(totalFormat, boldFont);
    xlFormatSetFillPattern(totalFormat, FILLPATTERN_SOLID);
    xlFormatSetPatternForegroundColor(totalFormat, COLOR_YELLOW);
    
    signatureFormat = xlBookAddFormat(book, 0);
    xlFormatSetAlignH(signatureFormat, ALIGNH_CENTER);
    xlFormatSetBorderTop(signatureFormat, BORDERSTYLE_THIN);
    
    sheet = xlBookAddSheet(book, "Invoice", 0);
    if(sheet)
    {
        xlSheetWriteStr(sheet, 2, 1, "Invoice No. 3568", titleFormat);
        
        xlSheetWriteStr(sheet, 4, 1, "姓名: John Smith", NULL);
        xlSheetWriteStr(sheet, 5, 1, "Address: San Ramon, CA 94583 USA", 0);
        
        xlSheetWriteStr(sheet, 7, 1, "Description", headerFormat);
        xlSheetWriteStr(sheet, 7, 2, "Amount", headerFormat);
        
        xlSheetWriteStr(sheet, 8, 1, "Ball-Point Pens", descriptionFormat);
        xlSheetWriteNum(sheet, 8, 2, 85, amountFormat);
        xlSheetWriteStr(sheet, 9, 1, "T-Shirts", descriptionFormat);
        xlSheetWriteNum(sheet, 9, 2, 150, amountFormat);
        xlSheetWriteStr(sheet, 10, 1, "Tea cups", descriptionFormat);
        xlSheetWriteNum(sheet, 10, 2, 45, amountFormat);
        
        xlSheetWriteStr(sheet, 11, 1, "Total:", totalLabelFormat);
        xlSheetWriteFormula(sheet, 11, 2, "=SUM(C9:C11)", totalFormat);
        
        xlSheetWriteStr(sheet, 14, 2, "Signature", signatureFormat);
        
        xlSheetSetCol(sheet, 1, 1, 40, 0, 0);
        xlSheetSetCol(sheet, 2, 2, 15, 0, 0);
    }
    
    NSString *name = xlsMode ? @"invoice.xls" : @"invoice.xlsx";
    NSString *documentPath =
    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filename = [documentPath stringByAppendingPathComponent:name];
    
    xlBookSave(book, [filename UTF8String]);
    
    xlBookRelease(book);
    
    [[NSWorkspace sharedWorkspace] openFile:filename];
}



@end
